/*
 * Licensed under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.submarine.exchange;

import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

import org.submarine.common.ServiceLoaderHelper;
import org.submarine.common.URL;
import org.submarine.registry.AbstractRegistry;
import org.submarine.registry.RegistryFactory;
import org.submarine.registry.listener.NotifyListener;
import org.submarine.transport.Endpoint;
import org.submarine.transport.netty.NettyClient;

/**
 * @file org.submarine.exchange.Agent.java
 *
 * Agent
 * 
 * @author gaojian
 * @created 2013-8-21 下午4:28:45
 * @version 0.0.1
 * @since 0.0.1
 * 
 */
public class Agent {
	
	private boolean running = true;
	
	private final CircularAtomicInteger index = new CircularAtomicInteger(1);
	
	private ConcurrentHashMap<URL, Set<URL>> collectors = new ConcurrentHashMap<URL, Set<URL>>();
	
	private synchronized Endpoint getClient(URL url) {
		return ServiceLoaderHelper.ENDPOINT_FACTORY.iterator().next().getClient(url, ExchangeFactory.getSender());
	}
	
	/**
	 * 
	 * TODO
	 *
	 * @author gaojian
	 * @created 2013年8月25日 上午1:17:14
	 *
	 * @param data
	 * @return
	 * @throws InterruptedException
	 */
	public Response invokeSync(Object data) throws InterruptedException {
		URL url = selectCollectorURL();
		if (null == url) {
			throw new RuntimeException("No collectors.");
		}
		NettyClient client = (NettyClient)getClient(url);
		Response response = client.invokeSync(url, Request.createRequest(data), 3000);
		return response;
	}
	
	private void registry(AbstractRegistry registry) {
		collectors.put(URL.localURL(), registry.getInitCollectorURL());
		registry.register(URL.localURL());//或者使用SubmarineContext
		registry.subscribe(URL.localURL(), new NotifyListener() {
			@Override
			public void notify(Set<URL> urls) {
				collectors.put(URL.localURL(), urls);
			}
		});
	}
	
	/**
	 * 
	 * 随机选择一个collector的URL
	 *
	 * @author gaojian
	 * @created 2013-8-21 下午11:17:44
	 *
	 * @return
	 */
	private URL selectCollectorURL() {
		URL[] urls = collectors.get(URL.localURL()).toArray(new URL[0]);
		if (0 == urls.length) {
			return null;
		}
		return urls[index.getAndIncrement() % urls.length];
	}
	
	/**
	 * 
	 * 启动
	 *
	 * @author gaojian
	 * @created 2013-8-21 下午4:33:32
	 *
	 */
	public void start() {
		RegistryFactory registryFactory = ServiceLoaderHelper.REGISTRY_FACTORY.iterator().next();
		AbstractRegistry registry = registryFactory.createRegistry(URL.localURL());
		registry(registry);
//		Runtime.getRuntime().addShutdownHook(new Thread() {
//			public void run() {
//				System.out.println("ShutdownHook");//FIXME(to delete)
//				try {
//					Agent.this.stop();
//					running = false;
//				} catch (Throwable t) {
//					t.printStackTrace();
//				}
//			}
//		});
	}

	/**
	 * @return the running
	 */
	public boolean isRunning() {
		return running;
	}

}

class CircularAtomicInteger {
	
	private final AtomicInteger ai;
	
	private final int initialValue;
	
	public CircularAtomicInteger(int initialValue) {
		ai = new AtomicInteger(initialValue);
		this.initialValue = initialValue;
	}
	
	public final int getAndIncrement() {
		if (ai.get() < Integer.MAX_VALUE) {
			return ai.getAndIncrement();
		} else {
			return ai.getAndSet(initialValue);
		}
	}

}